package cn.yqx.bankshop.order.service.impl;

import cn.yqx.bankshop.order.dao.BuGoodsAddressMapper;
import cn.yqx.bankshop.order.page.PageRequest;
import cn.yqx.bankshop.order.page.PageResult;
import cn.yqx.bankshop.order.page.PageUtils;
import cn.yqx.bankshop.order.pojo.BuGoodsAddress;
import cn.yqx.bankshop.order.pojo.BuGoodsAddressExample;
import cn.yqx.bankshop.order.service.AddressService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class AddressServiceImpl implements AddressService {
    private static final Integer  IS_EFFECTIVE = 1 ;
    @Autowired
    BuGoodsAddressMapper mapper ;
    @Override
    public PageResult findAddressByUserId(PageRequest pageRequest , Map<String,Object> map) {
        return  PageUtils.getPageResult(pageRequest, getPageInfo(pageRequest,map)) ;
    }

    @Override
    public int saveAddress(BuGoodsAddress address) {
        BuGoodsAddressExample example = new BuGoodsAddressExample() ;
        example.or().andUserIdEqualTo(address.getUserId()).andDeliveryNameEqualTo(address.getDeliveryName()).andAddressEqualTo(address.getAddress()) ;
        List<BuGoodsAddress> list = mapper.selectByExample(example) ;
        if(list.isEmpty()){
            address.setCreateTime(new Date());
            address.setIsEffective(IS_EFFECTIVE);
            return mapper.insert(address);
        }else{
            return -1 ;
        }
    }

    @Override
    public int updateAddress(BuGoodsAddress address) {
        return mapper.updateByPrimaryKey(address);
    }

    @Override
    public int setIsDefault(Long id,Long userId) {
        BuGoodsAddressExample example = new BuGoodsAddressExample() ;
        example.or().andIdEqualTo(id).andUserIdEqualTo(userId) ;
        BuGoodsAddress address = new BuGoodsAddress() ;
        address.setIsDefault(1);
        int flag = -1 ;
        flag =  mapper.updateByExampleSelective(address,example) ;
        BuGoodsAddressExample example1 = new BuGoodsAddressExample() ;
        example1.or().andIdNotEqualTo(id).andUserIdEqualTo(userId) ; ;
        address.setIsDefault(0);
        flag += mapper.updateByExampleSelective(address,example1) ;
        return flag;
    }

    @Override
    public int deleteAddress(Long id) {
        return mapper.deleteByPrimaryKey(id);
    }

    /**
     * 调用分页插件完成分页
     * @return
     */
    private PageInfo<BuGoodsAddress> getPageInfo(PageRequest pageRequest, Map<String,Object> map) {
        int pageNum = pageRequest.getPageNum();
        int pageSize = pageRequest.getPageSize();
        PageHelper.startPage(pageNum, pageSize);

        List<BuGoodsAddress> addresses = mapper.findAddressByUserId(map);
        return new PageInfo<BuGoodsAddress>(addresses);
    }
}
